#!/bin/bash
# Begin serve
##############
#$# creator : Devon Smith
#%# email: smithde@oclc.org
#$# created : 2010-06-18
#$# title : serve
#$# description : Serve the content of current directory via HTTP. See also: stop
########## Define a usage function 
function usage {
    echo "Usage: $this"
    if [ "$1" = "exit" ]; then exit; fi
}
########## Set to "false" to turn verbose off
function echo_stdout { echo "$@"; }
function echo_stderr { echo "$@" >& 2; }
# Set verbose to 'echo_stderr' or 'echo_stdout' to see output trace info
verbose=false
$verbose Verbose output on ${verbose##*_}

########## Setup some common paths
# The absolute, canonical ( no ".." ) path to this script
canonical=$(cd -P -- "$(dirname -- "$0")" && printf '%s\n' "$(pwd -P)/$(basename -- "$0")")
# Just the filename of this script
this=$(basename $canonical)
$verbose This: $this
# The directory this script is in
here=$(dirname $canonical)
$verbose Here: $here

########## When the script is being executed
today=$(date +%F)
now=$(date +%H:%M:%S)
$verbose Time: $today $now
##########
if [ "$1" = "-h" ]; then usage 'exit' ; fi
##########

if [ -f serve.pid ]; then echo "Server already running at http://localhost:"$(cat serve.port)"/"; exit; fi

PYTHON=$(which python)
PORT=8001

# Starting at 8001, look for an unused port
while true
do
	netstat -an | grep $PORT > /dev/null 2>&1
	if [ "0" = "$?" ]
	then
		PORT=$((PORT+1))
	else
		break
	fi
done

$verbose Serving on port $PORT
echo Content available at http://localhost:$PORT/
$PYTHON -m SimpleHTTPServer $PORT > /dev/null 2>&1 &
echo $! > serve.pid
echo $PORT > serve.port

############
# End serve
# vim:ts=4:indentexpr=
